#include "musicplayer.h"

MusicPlayer::MusicPlayer(const char* filename)
    :mCurrentPos(0),mDataLen(0),mDataBuffer(nullptr),mDevice(0)
{
     /* Load the WAV */
    if (SDL_LoadWAV(filename, &mSpec, &mDataBuffer, &mDataLen) == NULL) 
    {
        fprintf(stderr, "Could not open wav file: %s\n", SDL_GetError());
        //exit
    } 
    mSpec.callback=&MusicPlayer::callback;
    mSpec.userdata = this;
    mDevice = SDL_OpenAudioDevice(NULL, SDL_FALSE, &mSpec, NULL, 0);
    if (mDevice == 0) 
    {
        SDL_Log("Failed to open audio: %s", SDL_GetError());
    }
}

MusicPlayer::~MusicPlayer()
{
    SDL_FreeWAV(mDataBuffer);
    SDL_CloseAudioDevice(mDevice);
}

void MusicPlayer::callback(void *music_player, Uint8 * stream, int len)
{
    Uint8 *waveptr;
    int waveleft;
    
    auto obj = reinterpret_cast<MusicPlayer*>(music_player);

    // printf("len:%d,soundpos:%d,total:%d\n",len,obj->getCurrentPos(),obj->getDataLen());
    /* Set up the pointers */
    waveptr = obj->getDataBuffer() + obj->getCurrentPos();
    waveleft = obj->getDataLen() - obj->getCurrentPos();

    /* Go! */
    while (waveleft <= len) {
        SDL_memcpy(stream, waveptr, waveleft);
        stream += waveleft;
        len -= waveleft;
        waveptr = obj->getDataBuffer();
        waveleft = obj->getDataLen();
        obj->setCurrentPos(0);
    }
    SDL_memcpy(stream, waveptr, len);
    obj->setCurrentPos(obj->getCurrentPos() + len);
    obj->mDevice;
}
